package com.dhecp.project.api.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dhecp.common.utils.CacheUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.utils.MathExtUtils;
import com.dhecp.project.api.domain.Api1688ToKen;
import com.dhecp.project.api.domain.ApiResponse;
import com.dhecp.project.api.domain.Distribution;
import com.dhecp.project.api.domain.PurchaseOrder;
import com.dhecp.project.api.domain.PurchaseOrderSon;
import com.dhecp.project.api.domain.PurchasePlan;
import com.dhecp.project.api.mapper.Api1688ToKenMapper;
import com.dhecp.project.api.mapper.CompanyInfoMapper;
import com.dhecp.project.api.mapper.DistributionMapper;
import com.dhecp.project.api.mapper.PurchaseOrderMapper;
import com.dhecp.project.api.service.Api1688Service;
import com.dhecp.project.api.service.ApiLogService;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.api.util.ApiHmacSHA1Utils;
import com.dhecp.project.api.util.ApiHttpUtils;

/**
 * @ClassName Api1688ServiceImpl
 * @Author alula
 * @Date 2022-08-26 17:07
 */

@Service
public class Api1688ServiceImpl implements Api1688Service {

    private static final Logger logger = LoggerFactory.getLogger(Api1688ServiceImpl.class);
    //获取ACCESS_TOKEN址址
    public final static String ACCESS_TOKEN_URL = "https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/YOUR_APPKEY?grant_type=authorization_code&need_refresh_token=true&client_id=YOUR_APPKEY&client_secret=YOUR_APPSECRET&redirect_uri=YOUR_REDIRECT_URI&code=CODE";
    //刷新ACCESS_TOKEN地址
    public final static String REFRESH_TOKEN_URL = "https://gw.open.1688.com/openapi/param2/1/system.oauth2/getToken/YOUR_APPKEY?grant_type=refresh_token&client_id=YOUR_APPKEY&client_secret=YOUR_APPSECRET&refresh_token=REFRESH_TOKEN";
    //根据产品ID获取产品信息
    public final static String GET_PRODUCINFOURL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.cross.productInfo/YOUR_APPKEY";
    //将产品ID铺货到产品列表中
    public final static String PUSH_PRODUCINFOURL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.product.push/alibaba.cross.syncProductListPushed/YOUR_APPKEY";
    //创建采购订单
    public final static String CREATE_ORDER_URL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.trade/alibaba.trade.createCrossOrder/YOUR_APPKEY";
    //取消采购订单
    public final static String CANCEL_ORDER_URL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.trade/alibaba.trade.cancel/YOUR_APPKEY";
    //订单详细
    public final static String GET_ORDERDETAIL_URL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.trade/alibaba.trade.get.buyerView/YOUR_APPKEY";
    //订单物流信息
    public final static String GET_ORDERLOGISTICSINFO_URL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsInfos.buyerView/YOUR_APPKEY";
    //订单物流跟踪信息
    public final static String GET_ORDERTRACEINFO_URL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsTraceInfo.buyerView/YOUR_APPKEY";
    //获取订单支付URL地址
    public final static String GET_ORDERALIPAY_URL = "http://gw.open.1688.com/openapi/param2/1/com.alibaba.trade/alibaba.alipay.url.get/YOUR_APPKEY";

    @Autowired
    private Api1688ToKenMapper api1688ToKenMapper;

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private DistributionMapper distributionMapper;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    /**
     * 获取1688物流状态中英文信息
     *
     * @param logisticsState
     */
    private String getAliLogisticsStateName(String logisticsState) {
        String resultName = "";
        if (logisticsState.toUpperCase().contains("WAITACCEPT")) {
            resultName = logisticsState + "-未受理";
        } else if (logisticsState.toUpperCase().contains("CANCEL")) {
            resultName = logisticsState + "-已撤销";
        } else if (logisticsState.toUpperCase().contains("ACCEPT")) {
            resultName = logisticsState + "-已受理";
        } else if (logisticsState.toUpperCase().contains("TRANSPORT")) {
            resultName = logisticsState + "-运输中";
        } else if (logisticsState.toUpperCase().contains("NOGET")) {
            resultName = logisticsState + "-揽件失败";
        } else if (logisticsState.toUpperCase().contains("SIGN")) {
            resultName = logisticsState + "-已签收";
        } else if (logisticsState.toUpperCase().contains("UNSIGN")) {
            resultName = logisticsState + "-签收异常";
        } else {
            resultName = logisticsState;
        }
        return resultName;
    }

    /**
     * 获取1688支付状态中英信息
     *
     * @param payState
     * @return
     */
    private String getAliPaymentStateName(String payState) {
        String resultName = "";
        if (payState.toUpperCase().contains("ACCOUNT_BALANCE_NOT_ENOUGH")) {
            resultName = payState + "-余额不足";
        } else if (payState.toUpperCase().contains("ACCOUNT_NOT_EXIST")) {
            resultName = payState + "-跨境宝2.0场景下可能签约但是在ipay没有开户";
        } else if (payState.toUpperCase().contains("ACCOUNT_FROZEN")) {
            resultName = payState + "-账户冻结";
        } else if (payState.toUpperCase().contains("PARAM_ILLEGAL")) {
            resultName = payState + "-参数非法";
        } else if (payState.toUpperCase().contains("successed")) {
            resultName = payState + "-支付成功";
        }
        return resultName;
    }


    @Override
    public ApiResponse get1688Token(String code) {
        ApiResponse apiResponse = new ApiResponse();
        if (StringUtils.isEmpty(code)) {
            apiResponse.setCode(400);
            apiResponse.setMessage("通过code换取token时，code值不能为空！");
            return apiResponse;
        }
        String tokenExpiresKey = "access_token_Expires";
        String tokenKey = "access_token_1688";
        String redirectUrl = ACCESS_TOKEN_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey()).replace("YOUR_APPSECRET", ApiConfig.get1688AppSecret()).replace("YOUR_REDIRECT_URI", "").replace("CODE", code);
        JSONObject jsonObject = ApiHttpUtils.sendGet(redirectUrl);
        logger.error("通过code值[" + code + "]值获取到的token结果为" + jsonObject);
        Api1688ToKen model = null;
        if (jsonObject != null) {
            String access_token = jsonObject.getString("access_token");
            String aliId = jsonObject.getString("aliId");
            String refresh_token = jsonObject.getString("refresh_token");
            String resource_owner = jsonObject.getString("resource_owner");
            String expires_in = jsonObject.getString("expires_in");
            String refresh_token_timeout = jsonObject.getString("refresh_token_timeout");
            String memberId = jsonObject.getString("memberId");
            Date refreshTokenDate = null;
            //处理刷新token过期时间，转换成正常的时间格式
            if (!StringUtils.isEmpty(refresh_token_timeout) && refresh_token_timeout.length() >= 8) {
                String refresh_token_timeout2 = refresh_token_timeout.substring(0, refresh_token_timeout.length() - 8);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                LocalDateTime localDate = LocalDateTime.parse(refresh_token_timeout2, formatter);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                try {
                    refreshTokenDate = simpleDateFormat.parse(localDate.toString());
                } catch (Exception ex) {
                }
            }
            CacheUtils.put(tokenKey, access_token);//获取最新凭证
            CacheUtils.put(tokenExpiresKey, new Date(System.currentTimeMillis() + 60 * 60 * 1000 * 9));//设置凭证有效期为当前时间+9小时
            Api1688ToKen queryApi1688ToKen = api1688ToKenMapper.findApi1688TokenByOneData();
            if (queryApi1688ToKen == null) {
                model = new Api1688ToKen();
                model.setAccessToken(access_token);
                model.setAliId(aliId);
                model.setRefreshToken(refresh_token);
                model.setResourceOwner(resource_owner);
                model.setExpiresIn(expires_in);
                model.setRefreshTokenTimeout(refresh_token_timeout);
                model.setMemberId(memberId);
                model.setRefreshTokenDate(refreshTokenDate);
                api1688ToKenMapper.insert(model);
            } else {
                model = new Api1688ToKen();
                model.setId(queryApi1688ToKen.getId());
                model.setAccessToken(access_token);
                model.setAliId(aliId);
                model.setRefreshToken(refresh_token);
                model.setResourceOwner(resource_owner);
                model.setExpiresIn(expires_in);
                model.setRefreshTokenTimeout(refresh_token_timeout);
                model.setMemberId(memberId);
                model.setRefreshTokenDate(refreshTokenDate);
                api1688ToKenMapper.update(model);
            }
            apiResponse.setCode(0);
            apiResponse.setSuccess(true);
            apiResponse.setMessage("通过code换取token成功！");
        } else {
            apiResponse.setCode(400);
            apiResponse.setMessage("通过code换取token失败！");
        }
        return apiResponse;
    }

    /**
     * 调用1688相应业务接口时，获取已存在的token值
     *
     * @return
     */
    private String getCacheAccessToken() {
        String tokenExpiresKey = "access_token_Expires";
        String tokenKey = "access_token_1688";
        String token = "";
        if (CacheUtils.get(tokenExpiresKey) == null || CacheUtils.get(tokenExpiresKey).equals("") || new Date().after((Date) CacheUtils.get(tokenExpiresKey))) {//缓存中不存在凭证有效期或失效
            //1688token过期，需要从数据库获取到refresh_token，重新获取新的token值
            Api1688ToKen queryApi1688ToKen = api1688ToKenMapper.findApi1688TokenByOneData();
            if (queryApi1688ToKen != null) {//cache缓存中token过期，通过refreshtoken去获取新的token
                String redirectUrl = REFRESH_TOKEN_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey()).replace("YOUR_APPSECRET", ApiConfig.get1688AppSecret()).replace("REFRESH_TOKEN", queryApi1688ToKen.getRefreshToken());
                JSONObject jsonObject = ApiHttpUtils.sendGet(redirectUrl);
                logger.error("通过refresh_token值获取新的token结果为" + jsonObject);
                if (jsonObject != null) {
                    boolean success = true;
                    if (jsonObject.containsKey("success")) {
                        success = jsonObject.getBoolean("success");
                    }
                    if(success == true) {
                        token = jsonObject.getString("access_token");
                        Map<String, Object> updateMap = new HashMap<>();
                        updateMap.put("id", queryApi1688ToKen.getId());
                        updateMap.put("accessToken", token);
                        api1688ToKenMapper.updateByAccessToken(updateMap);
                        CacheUtils.put(tokenKey, token);//刷新获取最新凭证，存在缓存
                        CacheUtils.put(tokenExpiresKey, new Date(System.currentTimeMillis() + 60 * 60 * 1000 * 9));//设置凭证有效期为当前时间+9小时
                    }
                }
            }
        } else {
            token = CacheUtils.get(tokenKey).toString();
        }
        return token;
    }

    @Override
    public String getRefreshAccessToken() {
        //1688token过期，需要从数据库获取到refresh_token，重新获取新的token值
        String token = "";
        Api1688ToKen queryApi1688ToKen = api1688ToKenMapper.findApi1688TokenByOneData();
        if (queryApi1688ToKen != null) {
            if (new Date().after(queryApi1688ToKen.getRefreshTokenDate()) == false) {//refresh_token没有过期
                String redirectUrl = REFRESH_TOKEN_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey()).replace("YOUR_APPSECRET", ApiConfig.get1688AppSecret()).replace("REFRESH_TOKEN", queryApi1688ToKen.getRefreshToken());
                JSONObject jsonObject = ApiHttpUtils.sendGet(redirectUrl);
                logger.error("通过refresh_token值获取新的token结果为" + jsonObject);
                if (jsonObject != null) {
                    token = jsonObject.getString("access_token");
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("id", queryApi1688ToKen.getId());
                    updateMap.put("accessToken", token);
                    api1688ToKenMapper.updateByAccessToken(updateMap);
                }
            }
        }
        return token;
    }

    private String get1688ResourceOwner() {
        return "ease逸思电商";
    }

    @Override
    @Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)
    public ApiResponse get1688ProductDetail(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String productNos = (String) dataParams.get("productNos");
            String userId = (String) dataParams.get("userId");
            String pCode = (String) dataParams.get("pCode");
            String pName = (String) dataParams.get("pName");
            if (StringUtils.isEmpty(productNos) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(pCode) || StringUtils.isEmpty(pName)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("数据参数中productNos，userId，pcode，pname不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String[] productArray = productNos.split(",");
            List<String> errorNoList = new ArrayList<>();
            for (String productNo : productArray) {
                Long productId = TypeUtils.getSafeLong(productNo, 0L);
                if (productId > 0) {
                    boolean result = get1688ProductDetailByApi(productId, pCode, pName, system, type);
                    if (result == false) {
                        errorNoList.add(productNo);
                    }
                }
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            String message = "获取1688商品信息成功！";
            if (errorNoList.size() > 0) {
                message = message + "，其中失败的商品编号为[" + String.join(",", errorNoList) + "]";
            }
            apiResponse.setMessage(message);
            apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取1688商品信息接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用获取1688商品信息接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 获取单个商品信息
     *
     * @param productId
     * @param system
     * @param type
     * @return
     */
    private boolean get1688ProductDetailByApi(Long productId, String pCode, String pName, String system, String type) {
        boolean prodResult = false;
        if (productId <= 0) {
            return prodResult;
        }
        long aop_timestamp = new Date().getTime();
        String token = getCacheAccessToken();
        //铺货POST参数
        Map<String, String> pushPostParams = null;
        pushPostParams = new HashMap<>();
        long[] productIdList = new long[1];
        productIdList[0] = productId;
        pushPostParams.put("productIdList", JSON.toJSONString(productIdList));
        pushPostParams.put("access_token", token);
        pushPostParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        String push_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.product.push/alibaba.cross.syncProductListPushed/" + ApiConfig.get1688AppKey(), pushPostParams, ApiConfig.get1688AppSecret());
        pushPostParams.put("_aop_signature", push_signature);
        //获取产品信息参数
        Map<String, String> postParams = null;
        postParams = new HashMap<>();
        postParams.put("productId", String.valueOf(productId));
        postParams.put("access_token", token);
        postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.product/alibaba.cross.productInfo/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
        postParams.put("_aop_signature", aop_signature);
        try {
            if (StringUtils.isEmpty(token)){
                apiLogService.addApiLog(system, type, "调用1688将商品加入铺货列表-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(pushPostParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
                return prodResult;
            }
            String pushUrl = PUSH_PRODUCINFOURL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
            JSONObject pushJsonObject = ApiHttpUtils.sendHttpClientPost(pushUrl, pushPostParams);
            if (pushJsonObject == null) {
            	apiLogService.addApiLog(system, type, "调用1688将商品加入铺货列表-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(pushPostParams), JSON.toJSONString(pushJsonObject), 400, "调用1688将商品加入铺货列表接口出错，结果返回传JSON对象出错！");
                return prodResult;
            }
            JSONObject pushResultItemObject = pushJsonObject.getJSONObject("result");
            if (pushResultItemObject != null) {
                boolean pushSuccess = false;
                if (pushResultItemObject.containsKey("success")) {
                    pushSuccess = pushResultItemObject.getBoolean("success");
                }
                if (pushSuccess == true) {
                    String url = GET_PRODUCINFOURL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
                    JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
                    if (jsonObject == null) {
                    	apiLogService.addApiLog(system, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 400, "调用1688获取产品信息接口出错，结果返回传JSON对象出错！");
                        return prodResult;
                    }
                    boolean success = false;
                    if (jsonObject.containsKey("success")) {
                        success = jsonObject.getBoolean("success");
                    }
                    if (success == false) {
                        String errorMsg = "";
                        if (jsonObject.containsKey("message")) {
                            errorMsg = jsonObject.getString("message");
                        }
                        if (jsonObject.containsKey("error_message")) {
                            errorMsg = jsonObject.getString("error_message");
                        }
                        apiLogService.addApiLog(system, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 400, "调用1688获取产品信息接口出错，具体错误为:" + errorMsg);
                        return prodResult;
                    }
                    List<Distribution> insertDataList = new ArrayList<>();
                    Distribution distribution = null;
                    JSONObject productInfoObj = jsonObject.getJSONObject("productInfo");
                    if (productInfoObj != null) {
                        String productID = productInfoObj.get("productID").toString();
                        String status = (String) productInfoObj.get("status");
                        String subject = (String) productInfoObj.get("subject");
                        String supplierUserId = (String) productInfoObj.get("supplierUserId");
                        String supplierLoginId = (String) productInfoObj.get("supplierLoginId");
                        String images = "";
                        Integer minOrderQuantity = 0;
                        String saleType = "";
                        //处理图片
                        Map<String, Object> image = (Map<String, Object>) productInfoObj.get("image");
                        if (image != null) {
                            JSONArray imageArray = (JSONArray) image.get("images");
                            if (imageArray != null && imageArray.size() > 0) {
                                for (int i = 0; i < imageArray.size(); i++) {
                                    String itemImg = (String) imageArray.get(i);
                                    images += "https://cbu01.alicdn.com/" + itemImg + "|";
                                }
                            }
                        }
                        //处理最小起订量
                        JSONObject saleInfo = productInfoObj.getJSONObject("saleInfo");
                        if (saleInfo != null) {
                            minOrderQuantity = saleInfo.getInteger("minOrderQuantity");
                            saleType = saleInfo.getString("saleType");
                        }
                        //处理SKU
                        List<Map<String, Object>> skuList = (List<Map<String, Object>>) productInfoObj.get("skuInfos");
                        if(skuList != null && skuList.size() > 0) {
                            for (Map<String, Object> skuItem : skuList) {
                                distribution = new Distribution();
                                String skuCode = (String) skuItem.get("skuCode");
                                String skuId = skuItem.get("skuId").toString();
                                String specId = (String) skuItem.get("specId");
                                String skuName = "";
                                List<Map<String, Object>> skuPropertyList = (List<Map<String, Object>>) skuItem.get("attributes");
                                if (skuPropertyList != null && skuPropertyList.size() > 0) {
                                    for (Map<String, Object> skuNameItem : skuPropertyList) {
                                        String propValue = (String) skuNameItem.get("attributeValue");
                                        skuName += propValue + ";";
                                    }
                                }
                                if (!StringUtils.isEmpty(skuName) && skuName.length() > 0) {
                                    skuName = skuName.substring(0, skuName.length() - 1);
                                }
                                distribution.setGoodsID(productID);
                                distribution.setSupplierID(supplierUserId);
                                distribution.setSupplierLoginId(supplierLoginId);
                                distribution.setsKUID(skuId);
                                distribution.setsPECID(specId);
                                distribution.setName(subject);
                                distribution.setState(status);
                                distribution.setImages(images);
                                distribution.setsKUCODE(skuCode);
                                distribution.setsKUPRoperty(skuName);
                                distribution.setMinNum(minOrderQuantity);
                                distribution.setSalesMethod(saleType);
                                distribution.setaName(get1688ResourceOwner());
                                distribution.setpCode(pCode);
                                distribution.setpName(pName);
                                distribution.setCreateUser("0000");
                                insertDataList.add(distribution);
                            }
                        }else {//没有SKU插入一条SKUID跟商品ID一样，specId为空的数据
                            distribution = new Distribution();
                            distribution.setGoodsID(productID);
                            distribution.setSupplierID(supplierUserId);
                            distribution.setSupplierLoginId(supplierLoginId);
                            distribution.setsKUID(productID);
                            distribution.setsPECID("");
                            distribution.setName(subject);
                            distribution.setState(status);
                            distribution.setImages(images);
                            distribution.setsKUCODE(productID);
                            distribution.setsKUPRoperty("");
                            distribution.setMinNum(minOrderQuantity);
                            distribution.setSalesMethod(saleType);
                            distribution.setaName(get1688ResourceOwner());
                            distribution.setpCode(pCode);
                            distribution.setpName(pName);
                            distribution.setCreateUser("0000");
                            insertDataList.add(distribution);
                        }

                        //20230301日改成根据1688商品ID与系统商品ID为主键删除相应数据
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("goodsID", productID);
                        deleteMap.put("pCode", pCode);
                        distributionMapper.deleteDistributionByMap(deleteMap);
                        int insertLength = insertDataList.size();
                        int i = 0;
                        while (insertLength > 100) {
                            distributionMapper.insertBatchDistribution(insertDataList.subList(i, i + 100));
                            i = i + 100;
                            insertLength = insertLength - 100;
                        }
                        if (insertLength > 0) {
                            distributionMapper.insertBatchDistribution(insertDataList.subList(i, i + insertLength));
                        }
                    }
                    prodResult = true;
                } else {
                    prodResult = false;
                    String errorMsg = "";
                    if (pushJsonObject.containsKey("message")) {
                        errorMsg = pushJsonObject.getString("message");
                    }
                    if (pushJsonObject.containsKey("errorMsg")) {
                        errorMsg = pushJsonObject.getString("errorMsg");
                    }
                    apiLogService.addApiLog(system, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(pushPostParams), JSON.toJSONString(pushJsonObject), 400, "调用1688将商品加入铺货列表接口出错，具体错误为:" + errorMsg);
                }
            }
        } catch (Exception ex) {
            logger.error("ECP_API调用获取1688商品[" + String.valueOf(productId) + "]信息接口产出错，错误信息为：" + ex.getMessage());
            apiLogService.addApiLog(system, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用获取1688商品[" + String.valueOf(productId) + "]信息接口产出错，错误信息为：" + ex.getMessage());
        }
        return prodResult;
    }

    @Override
    public ApiResponse create1688Order(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), 0, "");
                return apiResponse;
            }
            String orderNos = (String) dataParams.get("orderNos");
            String userId = (String) dataParams.get("userId");
            if (StringUtils.isEmpty(orderNos) || StringUtils.isEmpty(userId)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("数据参数中orderNos与userId不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), 0, "");
                return apiResponse;
            }
            String[] orderNoList = orderNos.split(",");
            List<String> errorNoList = new ArrayList<>();
            Map<String, Object> invoiceParam = null;
            //从公司中取到1688收货地址与发票等信息
//            CompanyInfo companyInfo = companyInfoMapper.findCompanyInfoByVId("C101");
//            if (companyInfo == null){
//                apiResponse.setCode(400);
//                apiResponse.setMessage("公司编码C101对应的公司信息不存在，请维护！");
//                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
//                return apiResponse;
//            }
//            if (StringUtils.isEmpty(companyInfo.getvFhr()) || StringUtils.isEmpty(companyInfo.getvFhrDh()) || StringUtils.isEmpty(companyInfo.getvFhrSj()) || StringUtils.isEmpty(companyInfo.getvYbH()) || StringUtils.isEmpty(companyInfo.getvSfH()) || StringUtils.isEmpty(companyInfo.getvDsH())  || StringUtils.isEmpty(companyInfo.getvCqH()) || StringUtils.isEmpty(companyInfo.getvDzH()) ){
//                apiResponse.setCode(400);
//                apiResponse.setMessage("公司编码C101对应的收货人、电话、手机、邮编、省、市、县(区）、详细地址等不能为空！");
//                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
//                return apiResponse;
//            }
            //创建收货地址信息
            //1、先根据orderNo查询采购订单数据
            for (String item : orderNoList) {

                if (StringUtils.isEmpty(item)) {//订单号为空，直接跳过
                    continue;
                }

                PurchaseOrder purchaseOrder = purchaseOrderMapper.findPurchaseOrderByBid(item);
                PurchasePlan purchasePlan = purchaseOrderMapper.findByPlanId(purchaseOrder.getPlanID());

                Map<String, Object> addressParam = new HashMap<>();
                addressParam.put("fullName", purchasePlan.getvGsJc());
                addressParam.put("mobile", purchasePlan.getvFhrSj());
                addressParam.put("phone", purchasePlan.getPhone());
                addressParam.put("postCode", purchasePlan.getvYbH());
                addressParam.put("provinceText", purchasePlan.getvSfH());
                addressParam.put("cityText", purchasePlan.getvDsH());
                addressParam.put("areaText", purchasePlan.getvCqH());
                addressParam.put("townText", "");
                addressParam.put("address", purchasePlan.getvGsDz());
                //当发票设置类型不为-1时，创建发票信息
                if (!purchasePlan.getInvoiceType().equals("-1")) {
                    invoiceParam = new HashMap<>();
                    invoiceParam.put("invoiceType", purchasePlan.getInvoiceType());
                    invoiceParam.put("fullName", purchasePlan.getvSpr());
                    invoiceParam.put("mobile", purchasePlan.getvSprSj());
                    invoiceParam.put("phone", purchasePlan.getvSprDh());
                    invoiceParam.put("postCode", purchasePlan.getvYbP());
                    invoiceParam.put("provinceText", purchasePlan.getvSfP());
                    invoiceParam.put("cityText", purchasePlan.getvDsP());
                    invoiceParam.put("areaText", purchasePlan.getvCqP());
                    invoiceParam.put("townText", "");
                    invoiceParam.put("address", purchasePlan.getvDzP());
                    invoiceParam.put("companyName", purchasePlan.getvGsMc());
                    invoiceParam.put("taxpayerIdentifier", purchasePlan.getvTax());
                    if (purchasePlan.getInvoiceType().equals("1")) {
                        invoiceParam.put("bankAndAccount", (StringUtils.isEmpty(purchasePlan.getvBank()) ? "" : purchasePlan.getvBank()) + (StringUtils.isEmpty(purchasePlan.getvAccount()) ? "" : purchasePlan.getvAccount()));
                        invoiceParam.put("localInvoiceId", "");
                    }
                }

                boolean result;
                if (purchaseOrder.getAliResult().equals("创建成功")){
                    result = false;
                }else{
                    result = sendOrderDataTo1688(item, userId, system, type, addressParam, invoiceParam);
                }
//                boolean result = false;
                if (!result) {
                    errorNoList.add(item);
                }
            }

            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
//            String message = "["+orderNos+"]这些采购订单数据1688创建订单成功";
            String message = "创建成功";
            if (errorNoList.size() > 0) {
                message = message + "，其中失败的订单号为[" + String.join(",", errorNoList) + "]";
            }
            apiResponse.setMessage(message);
        } catch (Exception ex) {
        	ex.printStackTrace();
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用创建1688采购订单接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用创建1688采购订单接口出错，错误信息为：" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 单条创建1688订单
     *
     * @param orderNo
     * @param userId
     * @return
     */
    private boolean sendOrderDataTo1688(String orderNo, String userId, String system, String type, Map<String, Object> addressParam, Map<String, Object> invoiceParam) {
        boolean sendResult = false;
        Map<String, Object> updateMap = new HashMap<>();
        //1、先根据orderNo查询采购订单数据
        PurchaseOrder order = purchaseOrderMapper.findPurchaseOrderByBid(orderNo);
        if (order == null) {
            return false;
        }
        //对于已创建到1688的订单，直接返回true，不再重复创建
        if (!StringUtils.isEmpty(order.getAliOrderNumber())) {
            //return true;
        }
        //商品信息
        List<Map<String, Object>> cargoParamList = new ArrayList<>();
        Map<String, Object> cargoParamItem = null;
        Map<String, Object> queryOrderItemParam = new HashMap<>();
        queryOrderItemParam.put("pnid", order.getNid());
        List<PurchaseOrderSon> orderItemList = purchaseOrderMapper.findPurchaseOrderConList(queryOrderItemParam);
        StringBuffer errorProductMsg = new StringBuffer();
        String message = "";
        String shAddrExt = "";
        int k = 0;
        if (orderItemList != null && orderItemList.size() > 0) {
            for (PurchaseOrderSon orderItem : orderItemList) {
//                if (StringUtils.isEmpty(orderItem.getGoodsID()) || StringUtils.isEmpty(orderItem.getSpecId())) {
//                    errorProductMsg.append("子件商品[" + orderItem.getsCode() + "]的1688采购商品ID或者SpecId为空，请维护关系！");
//                    errorProductMsg.append("\r\n");
//                }
                //订单留言信息
                if (!StringUtils.isEmpty(orderItem.getRemark())) {
                    message += orderItem.getRemark() + ",";
                }
                //创建收货地址扩展采购单号与第一条子件商品编号
                if (k == 0) {
                    shAddrExt = orderNo + "," + orderItem.getsCode();
                }
                cargoParamItem = new HashMap<>();
                
                if (!StringUtils.isEmpty(orderItem.getSpecId())) {
                    cargoParamItem.put("specId", orderItem.getSpecId());
				}
                cargoParamItem.put("quantity", orderItem.getSum());
                cargoParamItem.put("offerId", orderItem.getGoodsID());
                cargoParamList.add(cargoParamItem);
                k++;
            }
        }
        if (orderItemList == null || orderItemList.size() == 0) {
            updateMap.put("bid", orderNo);
            updateMap.put("aliMessage", "");
            updateMap.put("aliResult", "创建失败");
            updateMap.put("aliErrorMessages", "此采购订单没有商品明细数据！");
            purchaseOrderMapper.updatePurchaseOrderToCreateOrder(updateMap);
            return false;
        }
        //子件商品1688采购商品ID或者SpecId为空，提示创建失败
        if (!StringUtils.isEmpty(errorProductMsg.toString())) {
            updateMap.put("bid", orderNo);
            updateMap.put("aliMessage", "");
            updateMap.put("aliResult", "创建失败");
            updateMap.put("aliErrorMessages", errorProductMsg.toString());
            purchaseOrderMapper.updatePurchaseOrderToCreateOrder(updateMap);
            return false;
        }
        //3、创建相应的post参数
        Map<String, String> postParams = new HashMap<>();
        String token = getCacheAccessToken();
        long aop_timestamp = new Date().getTime();
        postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        postParams.put("access_token", token);
        postParams.put("flow", "general");//流程
//        postParams.put("tradeType", "fxassure");// 交易类型 旧的
        postParams.put("tradeType", "assureTrade");// 交易类型-交易4.0通用担保交易
        //留言
        if (!StringUtils.isEmpty(message) && message.length() > 0) {
            postParams.put("message", message.substring(0, message.length() - 1));
        } else {
            postParams.put("message", "");
        }
        postParams.put("cargoParamList", JSON.toJSONString(cargoParamList));
        //收货地址
        //addressParam.put("address","吴屿路2号7号楼5层"+ "("+shAddrExt+")");
        if (addressParam != null) {
            //取收货人地址，加上扩展信息
            String shAddress = (String) addressParam.get("address");
            if (!StringUtils.isEmpty(shAddress)) {
                shAddress = shAddress + "(" + shAddrExt + ")";
                addressParam.put("address", shAddress);
            }
            postParams.put("addressParam", JSON.toJSONString(addressParam));
        }
        //发票信息
        if (invoiceParam != null) {
            postParams.put("invoiceParam", JSON.toJSONString(invoiceParam));
        }
        
        // 店铺优惠ID
        if (order.getAliPromotionId() != null && order.getAliPromotionId().length() > 0) {
            postParams.put("aliPromotionId", order.getAliPromotionId());
		}
        
        String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.createCrossOrder/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
        postParams.put("_aop_signature", aop_signature);
        try {
            if (StringUtils.isEmpty(token)){
            	apiLogService.addApiLog(system, type, "1688订单创建-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
                return false;
            }
            String url = CREATE_ORDER_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
            System.out.println(JSON.toJSONString(jsonObject));
            String errorMsg = "";
            if (jsonObject != null) {
                updateMap.put("bid", orderNo);
                updateMap.put("aliMessage", message);
                boolean success = false;
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getBoolean("success");
                }
                JSONObject orderResult = (JSONObject) jsonObject.get("result");
                if (success == true) {//成功处理
                    if (orderResult != null) {
                        String aliOrderNumber = orderResult.getString("orderId");
                        Long orderAmount = orderResult.getLong("totalSuccessAmount");
                        Long freightCharge = orderResult.getLong("postFee");
                        boolean itemSuccess = orderResult.getBoolean("success");
                        if (itemSuccess == true) {//订单内部正确标记
                            updateMap.put("aliResult", "创建成功");
                            updateMap.put("aliState", "waitbuyerpay");
                            updateMap.put("aliOrderNumber", aliOrderNumber);
                            BigDecimal orderAmountBig = BigDecimal.valueOf(orderAmount).divide(new BigDecimal(100));
                            updateMap.put("orderAmount", orderAmountBig.toString());
                            updateMap.put("freightCharge", BigDecimal.valueOf(freightCharge).divide(new BigDecimal(100)).toString());
                            updateMap.put("orderAmount2", orderAmountBig.toString());
                            updateMap.put("freightCharge2", BigDecimal.valueOf(freightCharge).divide(new BigDecimal(100)).toString());
                            updateMap.put("serviceCharge", MathExtUtils.fmtPrice(orderAmountBig.multiply(new BigDecimal("0.05")).doubleValue(),2));
                            sendResult = true;
                        } else {
                            updateMap.put("aliResult", "创建失败");
                            String itemMessage = orderResult.getString("message");
                            errorMsg = "创建订单失败，错误信息为：" + itemMessage;
                            JSONArray failedOfferList = orderResult.getJSONArray("failedOfferList");
                            if (failedOfferList != null && failedOfferList.size() > 0) {
                                errorMsg = errorMsg + "，具体商品失败信息如下：\n\r";
                                for (int i = 0; i < failedOfferList.size(); i++) {
                                    JSONObject failedItem = failedOfferList.getJSONObject(i);
                                    String itemOfferId = failedItem.getString("offerId");
                                    String itemSpecId = failedItem.getString("specId");
                                    String itemErrorMessage = failedItem.getString("errorMessage");
                                    errorMsg += "商品编号[" + itemOfferId + "]的下的specId为[" + itemSpecId + "]下单失败，具体错误为：" + itemErrorMessage + "\n\r";
                                }
                            }
                            sendResult = false;
                        }
                        updateMap.put("aliErrorMessages", errorMsg);
                    }
                } else {//失败处理
                    if (jsonObject.containsKey("message")) {
                        errorMsg = jsonObject.getString("message");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                    if (orderResult != null) {
                        JSONArray failedOfferList = orderResult.getJSONArray("failedOfferList");
                        if (failedOfferList != null && failedOfferList.size() > 0) {
                            errorMsg = errorMsg + "，具体失败信息如下：\n\r";
                            for (int i = 0; i < failedOfferList.size(); i++) {
                                JSONObject failedItem = failedOfferList.getJSONObject(i);
                                String itemSkuId = failedItem.getString("offerId");
                                String itemErrorMessage = failedItem.getString("errorMessage");
                                errorMsg += "商品[" + itemSkuId + "]下单失败，具体错误为：" + itemErrorMessage + "\n\r";
                            }
                        }
                    }
                    updateMap.put("aliResult", "创建失败");
                    updateMap.put("aliErrorMessages", errorMsg);
                    sendResult = false;
                }
                //更新订单相应字段
                purchaseOrderMapper.updatePurchaseOrderToCreateOrder(updateMap);
            }
        } catch (Exception ex) {
            logger.error("ECP_API调用创建1688采购订单接口创建[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
            apiLogService.addApiLog(system, type, "1688订单创建-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用创建1688采购订单接口创建[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
        }
        return sendResult;
    }

    @Override
    @Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)
    public ApiResponse cancel1688Order(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String orderNos = (String) dataParams.get("orderNos");
            String userId = (String) dataParams.get("userId");
            String cancelReason = (String) dataParams.get("cancelReason");
            if (StringUtils.isEmpty(orderNos) || StringUtils.isEmpty(userId)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("数据参数中orderNos与userId不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            if (StringUtils.isEmpty(cancelReason)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("数据参数中cancelReason取消原因不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
               TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String[] orderNoList = orderNos.split(",");
            List<String> errorNoList = new ArrayList<>();
            for (String orderNo : orderNoList) {
                if (StringUtils.isEmpty(orderNo)) {//订单号为空，直接跳过
                    continue;
                }
                boolean result = cancelOrderDataTo1688(orderNo, userId, cancelReason, system, type);
                if (result == false) {
                    errorNoList.add(orderNo);
                }
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            String message = "1688取消采购订单操作成功";
            if (errorNoList.size() > 0) {
                message = message + "，其中取消失败的订单号为[" + String.join(",", errorNoList) + "]";
            }
            apiResponse.setMessage(message);
            apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
         } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用取消1688采购订单接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用取消1688采购订单接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 单条取消1688订单
     *
     * @param orderNo
     * @param userId
     * @param cancelReason
     * @param system
     * @param type
     * @return
     */
    private boolean cancelOrderDataTo1688(String orderNo, String userId, String cancelReason, String system, String type) {
        boolean sendResult = false;
        Map<String, Object> updateMap = new HashMap<>();
        //1、先根据orderNo查询采购订单数据
        PurchaseOrder purchaseOrder = purchaseOrderMapper.findPurchaseOrderByBid(orderNo);
        if (purchaseOrder == null) {
            return false;
        }
        if (StringUtils.isEmpty(purchaseOrder.getAliOrderNumber())) {
            updateMap.put("bid", orderNo);
            updateMap.put("aliResult", "取消失败");
            updateMap.put("aliErrorMessages", "此订单没有1688的订单编号");
            purchaseOrderMapper.updatePurchaseOrderToCancelOrder(updateMap);
            return false;
        }
        Map<String, String> postParams = new HashMap<>();
        String token = getCacheAccessToken();
        long aop_timestamp = new Date().getTime();
        postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        postParams.put("access_token", token);
        postParams.put("webSite", "1688");
        postParams.put("tradeID", purchaseOrder.getAliOrderNumber());
        postParams.put("cancelReason", cancelReason);
        postParams.put("remark", "");
        String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.cancel/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
        postParams.put("_aop_signature", aop_signature);
        try {
            apiLogService.addApiLog(system, type, "1688订单取消-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 0, "");
            if (StringUtils.isEmpty(token)){
            	apiLogService.addApiLog(system, type, "1688订单取消-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
               return false;
            }
            String url = CANCEL_ORDER_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
            String errorMsg = "";
            if (jsonObject != null) {
                boolean success = false;
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getBoolean("success");
                }
                updateMap.put("bid", orderNo);
                if (success == true) {
                    updateMap.put("aliResult", "取消成功");
                    updateMap.put("aliOrderNumber", "");
                    updateMap.put("orderAmount", 0);
                    updateMap.put("freightCharge", 0);
                    updateMap.put("orderAmount2", 0);
                    updateMap.put("freightCharge2", 0);
                    updateMap.put("serviceCharge", 0);
                    updateMap.put("aliMessage", "");
                    updateMap.put("aliState", "");
                    updateMap.put("aliErrorMessages", "");
                    sendResult = true;
                } else {
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                    updateMap.put("aliResult", "取消失败");
                    updateMap.put("aliErrorMessages", errorMsg);
                    sendResult = false;
                }
                //保存取消信息
                purchaseOrderMapper.updatePurchaseOrderToCancelOrder(updateMap);
            }
        } catch (Exception ex) {
            logger.error("ECP_API调用取消1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
            apiLogService.addApiLog(system, type, "1688订单取消-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用创建1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
        }
        return sendResult;
    }

    @Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)
    @Override
    public ApiResponse get1688OrderDetail(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String orderNos = (String) dataParams.get("orderNos");
            String userId = (String) dataParams.get("userId");
            if (StringUtils.isEmpty(orderNos)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数orderNos不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String[] orderNoList = orderNos.split(",");
            List<String> errorNoList = new ArrayList<>();
            for (String orderNo : orderNoList) {
                if (StringUtils.isEmpty(orderNo)) {//订单号为空，直接跳过
                    continue;
                }
                boolean result = get1688OrderDetailByApi(orderNo, userId, system, type);
                if (result == false) {
                    errorNoList.add(orderNo);
                }
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            String message = "获取1688订单信息操作成功";
            if (errorNoList.size() > 0) {
                message = message + "，其中获取失败的订单号为[" + String.join(",", errorNoList) + "]";
            }
            apiResponse.setMessage(message);
//            apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取1688采购订单详细接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用获取1688采购订单详细接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 单条获取1688订单信息
     */
    private boolean get1688OrderDetailByApi(String orderNo, String userId, String system, String type){
        boolean sendResult = false;
        PurchaseOrder purchaseOrder = purchaseOrderMapper.findPurchaseOrderByBid(orderNo);
        if (purchaseOrder == null) {
            return false;
        }
        if (StringUtils.isEmpty(purchaseOrder.getAliOrderNumber())) {
            return false;
        }
        Map<String, String> postParams = new HashMap<>();
        String token = getCacheAccessToken();
        long aop_timestamp = new Date().getTime();
        postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        postParams.put("access_token", token);
        postParams.put("webSite", "1688");
        postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660419985562523597"
        String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.get.buyerView/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
        postParams.put("_aop_signature", aop_signature);
        try {
//            apiLogService.addApiLog(system, type, "1688订单信息-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 0, "");
            if (StringUtils.isEmpty(token)){
            	apiLogService.addApiLog(system, type, "1688订单信息-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
                return false;
            }
            String url = GET_ORDERDETAIL_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
            String errorMsg = "";
            if (jsonObject != null) {
                String success = "";
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getString("success");
                }
                if (success.toLowerCase().equals("true")) {
                    sendResult = true;
                    JSONObject orderResult = (JSONObject) jsonObject.get("result");
                    if (orderResult != null) {
                        Map<String, Object> updateMap = new HashMap<>();
                        updateMap.put("bid", orderNo);
                        JSONObject baseInfo = (JSONObject) orderResult.get("baseInfo");
                        //订单状态信息
                        if (baseInfo != null) {
                            updateMap.put("aliState", baseInfo.getString("status"));
                            if(purchaseOrder.getState().equals("待审核")) {//20230306未审核时，才会更新订单明细商品价格
                                BigDecimal orderAmountBig = baseInfo.getBigDecimal("totalAmount");
                                updateMap.put("orderAmount", orderAmountBig.toString());
                                updateMap.put("freightCharge", baseInfo.getBigDecimal("shippingFee").toString());
                                updateMap.put("serviceCharge", MathExtUtils.fmtPrice(orderAmountBig.multiply(new BigDecimal("0.05")).doubleValue(), 2));
                            }
                        }
                        //物流信息
                        JSONObject nativeLogistics = (JSONObject) orderResult.get("nativeLogistics");
                        if (nativeLogistics != null) {
                            JSONArray logisticsItems = (JSONArray) nativeLogistics.get("logisticsItems");
                            String aliLogisticsCompanyCode = "";
                            if (logisticsItems != null && logisticsItems.size() > 0) {
                                for (int i = 0; i < logisticsItems.size(); i++) {
                                    JSONObject logisticsItem = logisticsItems.getJSONObject(i);
                                    aliLogisticsCompanyCode += logisticsItem.getString("logisticsCompanyNo") + ',';
                                }
                                if (aliLogisticsCompanyCode.length() > 0) {
                                    aliLogisticsCompanyCode = aliLogisticsCompanyCode.substring(0, aliLogisticsCompanyCode.length() - 1);
                                }
                                updateMap.put("aliLogisticsCompanyCode", aliLogisticsCompanyCode);
                            }
                        }
                        purchaseOrderMapper.updatePurchaseOrderToInfo(updateMap);
                        //处理订单商品信息价格
                        if(purchaseOrder.getState().equals("待审核")) {//20230306未审核时，才会更新订单明细商品价格
                            JSONArray productItems = (JSONArray) orderResult.get("productItems");
                            if (productItems != null && productItems.size() > 0) {
                                Map<String, Object> updateItemMap = null;
                                for (int j = 0; j < productItems.size(); j++) {
                                    JSONObject productItem = productItems.getJSONObject(j);
                                    if (productItem != null) {
                                        String specId = productItem.getString("specId");
                                        String skuId = productItem.getString("skuID");
                                        Double price2 = productItem.getDouble("price");
                                        Integer quantity = productItem.getInteger("quantity");
                                        Double cost2 = MathExtUtils.fmtPrice(price2 * quantity, 2);
                                        updateItemMap = new HashMap<>();
                                        updateItemMap.put("pNid", purchaseOrder.getNid());
                                        updateItemMap.put("specId", specId);
                                        updateItemMap.put("skuId", skuId);
                                        updateItemMap.put("price2", price2);
                                        updateItemMap.put("cost2", cost2);
                                        //20230306增加获取下单后获取SKU属性进行对比
                                        JSONArray skuInfos = (JSONArray)productItem.get("skuInfos");
                                        if (skuInfos != null && skuInfos.size() > 0){
                                            String sku2Name = "";
                                            for (int k = 0; k < skuInfos.size(); k++) {
                                                JSONObject skuInfoItem = skuInfos.getJSONObject(k);
                                                sku2Name += skuInfoItem.getString("value")+";";
                                            }
                                            if (!StringUtils.isEmpty(sku2Name) && sku2Name.length() > 0){
                                                sku2Name = sku2Name.substring(0, sku2Name.length()-1);
                                            }
                                            updateItemMap.put("SKU2", sku2Name);
                                        }
                                        purchaseOrderMapper.updatePurchaseOrderSonToPrice(updateItemMap);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    sendResult = false;
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                }
            }
        }catch (Exception ex) {
            logger.error("ECP_API调用1688订单信息接口获取[" + orderNo + "]信息出错，错误信息为：" + ex.getMessage());
            apiLogService.addApiLog(system, type, "1688获取订单信息接口-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用1688订单信息接口获取[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
            sendResult = false;
        }
        return sendResult;
    }

    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    @Override
    public ApiResponse get1688OrderLogisticsInfo(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String orderNo = (String) dataParams.get("orderNo");
            if (StringUtils.isEmpty(orderNo)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数orderNo不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            PurchaseOrder purchaseOrder = purchaseOrderMapper.findPurchaseOrderByBid(orderNo);
            Map<String, String> postParams = new HashMap<>();
            if (purchaseOrder != null) {
                String token = getCacheAccessToken();
                if (StringUtils.isEmpty(token)){
                    apiResponse.setCode(400);
                    apiResponse.setMessage("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
                    apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                long aop_timestamp = new Date().getTime();
                postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
                postParams.put("access_token", token);
                postParams.put("webSite", "1688");
                postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660419985562523597"
                String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsInfos.buyerView/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
                postParams.put("_aop_signature", aop_signature);
                String url = GET_ORDERLOGISTICSINFO_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
                JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
                if (jsonObject == null) {
                    apiResponse.setCode(400);
                    apiResponse.setMessage("调用获取1688采购订单物流信息接口返回不是一个JSON对象！");
                    apiLogService.addApiLog(system, type, "获取1688订单物流详细-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                boolean success = false;
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getBoolean("success");
                }
                if (success == true) {
                    String errorMsg = "";
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (!StringUtils.isEmpty(errorMsg)) {
                        apiResponse.setCode(400);
                        apiResponse.setMessage(errorMsg);
                    } else {
                        apiResponse.setSuccess(true);
                        apiResponse.setCode(0);
                        JSONArray logisticsResult = (JSONArray) jsonObject.get("result");
                        if (logisticsResult != null && logisticsResult.size() > 0) {
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("bid", orderNo);
                            String aliLogisticsCompanyName = "";
                            String alilLogisticsBillNo = "";
                            String aliLogisticsCode = "";
                            String aliLogisticsState = "";
                            for (int i = 0; i < logisticsResult.size(); i++) {
                                JSONObject logisticsItem = logisticsResult.getJSONObject(i);
                                aliLogisticsState += getAliLogisticsStateName(logisticsItem.getString("status")) + ',';
                                aliLogisticsCompanyName += logisticsItem.getString("logisticsCompanyName") + ',';
                                alilLogisticsBillNo += logisticsItem.getString("logisticsBillNo") + ',';
                                aliLogisticsCode += logisticsItem.getString("logisticsId");
                            }
                            if (aliLogisticsState.length() > 0) {
                                aliLogisticsState = aliLogisticsState.substring(0, aliLogisticsState.length() - 1);
                            }
                            if (aliLogisticsCompanyName.length() > 0) {
                                aliLogisticsCompanyName = aliLogisticsCompanyName.substring(0, aliLogisticsCompanyName.length() - 1);
                            }
                            if (alilLogisticsBillNo.length() > 0) {
                                alilLogisticsBillNo = alilLogisticsBillNo.substring(0, alilLogisticsBillNo.length() - 1);
                            }
                            if (aliLogisticsCode.length() > 0) {
                                aliLogisticsCode = aliLogisticsCode.substring(0, aliLogisticsCode.length() - 1);
                            }
                            updateMap.put("aliLogisticsCompanyName", aliLogisticsCompanyName);
                            updateMap.put("aliLogisticsBillNo", alilLogisticsBillNo);
                            updateMap.put("aliLogisticsCode", aliLogisticsCode);
                            updateMap.put("aliLogisticsState", aliLogisticsState);
                            updateMap.put("aliPlace", aliLogisticsCompanyName);
                            purchaseOrderMapper.updatePurchaseOrderToLogistics(updateMap);
                        }
                    }
                } else {
                    String errorMsg = "";
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                    apiResponse.setCode(400);
                    apiResponse.setMessage("调用获取1688采购订单物流信息接口出错，具体错误为：" + errorMsg);
                }
           } else {
                apiResponse.setCode(400);
                apiResponse.setMessage("orderNo单号对应的订单不存在！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
            }
        } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取1688采购订单物流信息接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用获取1688采购订单物流信息接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    @Override
    public ApiResponse get1688OrderTraceInfo(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String orderNo = (String) dataParams.get("orderNo");
            if (StringUtils.isEmpty(orderNo)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数orderNo不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            PurchaseOrder purchaseOrder = purchaseOrderMapper.findPurchaseOrderByBid(orderNo);
            Map<String, String> postParams = new HashMap<>();
            if (purchaseOrder != null) {
                String token = getCacheAccessToken();
                if (StringUtils.isEmpty(token)){
                    apiResponse.setCode(400);
                    apiResponse.setMessage("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
                    apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                long aop_timestamp = new Date().getTime();
                postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
                postParams.put("access_token", token);
                postParams.put("webSite", "1688");
                postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660325666067523597"
                String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsTraceInfo.buyerView/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
                postParams.put("_aop_signature", aop_signature);
                String url = GET_ORDERTRACEINFO_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
                JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
                if (jsonObject == null) {
                    apiResponse.setCode(400);
                    apiResponse.setMessage("调用获取1688采购订单物流跟踪信息接口返回不是一个JSON对象！");
                    apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                boolean success = false;
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getBoolean("success");
                }
                if (success == true) {
                    String errorMsg = "";
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (!StringUtils.isEmpty(errorMsg)) {
                        apiResponse.setCode(400);
                        apiResponse.setMessage(errorMsg);
                    } else {
                        apiResponse.setSuccess(true);
                        apiResponse.setCode(0);
                        JSONArray logisticsTrace = (JSONArray) jsonObject.get("logisticsTrace");
                        if (logisticsTrace != null && logisticsTrace.size() > 0) {
                            //取索引为0的跟踪信息
                            JSONObject logisticsTraceItem = logisticsTrace.getJSONObject(0);
                            if (logisticsTraceItem != null) {
                                JSONArray logisticsSteps = logisticsTraceItem.getJSONArray("logisticsSteps");
                                apiResponse.setData(logisticsSteps);
                            }
                        }
                    }
                } else {
                    String errorMsg = "";
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                    apiResponse.setCode(400);
                    apiResponse.setMessage("调用获取1688采购订单物流跟踪信息接口出错，具体错误为：" + errorMsg);
                }
            } else {
                apiResponse.setCode(400);
                apiResponse.setMessage("orderNo单号对应的订单不存在！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
            }
        } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取1688采购订单物流跟踪信息接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用获取1688采购订单物流跟踪信息接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    @Override
    public ApiResponse get1688AlipayUrl(String system, String type, Map<String, Object> dataParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String aliOrderNos = (String) dataParams.get("aliOrderNos");
            if (StringUtils.isEmpty(aliOrderNos)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数aliOrderNos不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String[] orderNoArray = aliOrderNos.split(",");
            if (orderNoArray.length > 30) {
                apiResponse.setCode(400);
                apiResponse.setMessage("一次性最多只能支付30个1688订单！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            Long[] orderIdList = new Long[orderNoArray.length];
            int k = 0;
            for (String orderNo : orderNoArray) {
                if (!StringUtils.isEmpty(orderNo)) {//订单号不为空加入
                    orderIdList[k] = TypeUtils.getSafeLong(orderNo, 0L);
                    k++;
                }
            }
            Map<String, String> postParams = new HashMap<>();
            String token = getCacheAccessToken();
            if (StringUtils.isEmpty(token)){
                apiResponse.setCode(400);
                apiResponse.setMessage("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            long aop_timestamp = new Date().getTime();
            postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
            postParams.put("access_token", token);
            postParams.put("orderIdList", JSON.toJSONString(orderIdList));
            String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.alipay.url.get/" + ApiConfig.get1688AppKey(), postParams, ApiConfig.get1688AppSecret());
            postParams.put("_aop_signature", aop_signature);
            String url = GET_ORDERALIPAY_URL.replace("YOUR_APPKEY", ApiConfig.get1688AppKey());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
            if (jsonObject == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("调用获取1688支付URL接口返回不是一个JSON对象！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            boolean success = false;
            if (jsonObject.containsKey("success")) {
                success = jsonObject.getBoolean("success");
            }
            if (success == true) {
                apiResponse.setSuccess(true);
                apiResponse.setCode(0);
                String payUrl = jsonObject.getString("payUrl");
                apiResponse.setExtendAttr(payUrl);
            } else {
                String errorMsg = "";
                if (jsonObject.containsKey("erroMsg")) {
                    errorMsg = jsonObject.getString("erroMsg");
                }
                if (jsonObject.containsKey("error_message")) {
                    errorMsg = jsonObject.getString("error_message");
                }
                apiResponse.setCode(400);
                apiResponse.setMessage("调用获取1688支付URL接口出错，具体错误为：" + errorMsg);
            }
        } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取1688支付URL接口出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API调用获取1688支付URL接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    @Override
    public ApiResponse push1688Message(String system, String type, Map<String, Object> dataParams) {
synchronized (this) {
	
    	ApiResponse apiResponse = new ApiResponse();
        try {
            if (dataParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数dataParams不能为空！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            String message = (String) dataParams.get("message");
            String aop_signature = (String) dataParams.get("_aop_signature");
            Map<String, String> signParams = new HashMap<>();
            signParams.put("message", message);
            String newSignature = ApiHmacSHA1Utils.signatureWithParamsOnly(signParams, ApiConfig.get1688AppSecret());
            if (!newSignature.equals(aop_signature)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("_aop_signature签名参数验证失败！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            Map<String, Object> messageMap = JSONObject.parseObject(message, new TypeReference<Map<String, Object>>() {
            });
            if (messageMap == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("message参数不是一个有效的JSON字符串！");
                apiLogService.addApiLog(system, type, "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            Map<String, Object> updateMap = new HashMap<>();
            Map<String, Object> updateOrderMap = null;
            String messageType = (String) messageMap.get("type");
            Map<String, Object> dataMap = (Map<String, Object>) messageMap.get("data");
            switch (messageType) {
                case "ORDER_BATCH_PAY"://批量支付消息处理
                    JSONArray batchPayList = (JSONArray) dataMap.get("batchPay");
                    if (batchPayList != null && batchPayList.size() > 0) {
                        for (int i = 0; i < batchPayList.size(); i++) {
                            JSONObject itemObj = batchPayList.getJSONObject(i);
                            String orderId1 = (String) itemObj.get("orderId");
                            String status1 = (String) itemObj.get("status");
                            updateMap.put("aliOrderNumber", orderId1);
                            if (status1.equals("successed")) {
                                updateMap.put("aliResult", "支付成功");
                                updateMap.put("isPay", "已付款");
                                updateOrderMap = new HashMap<>();
                                updateOrderMap.put("aliOrderNumber", orderId1);
                                updateOrderMap.put("isPay", "已付款");
                            } else {
                                updateMap.put("aliResult", "支付失败");
                                updateMap.put("aliErrorMessages", getAliPaymentStateName(status1));
                            }
                            purchaseOrderMapper.updatePurchaseOrderPaymentPayStatusByAliOrderNo(updateMap);
                            //更新采购订单表的付款状态
                            if (updateOrderMap != null){
                                purchaseOrderMapper.updatePurchaseOrderPayStatusByAliOrderNo(updateOrderMap);
                            }
                        }
                    }
                    break;
                case "ORDER_BUYER_VIEW_ORDER_PAY"://1688交易付款（买家视角)
                    String orderId2 = dataMap.get("orderId").toString();
                    String status2 = (String) dataMap.get("currentStatus");
                    if (status2.equals("waitsellersend")) {//20230303增加判断，只有成功支付,20230313改成判断订单状态为waitsellersend时更新已付款（status2.equals("success"))
                        updateMap.put("aliOrderNumber", orderId2);
                        updateMap.put("aliResult", "支付成功");
                        updateMap.put("isPay", "已付款");
                        purchaseOrderMapper.updatePurchaseOrderPaymentPayStatusByAliOrderNo(updateMap);
                        updateOrderMap = new HashMap<>();
                        updateOrderMap.put("aliOrderNumber", orderId2);
                        updateOrderMap.put("isPay", "已付款");
                        //更新采购订单表的付款状态
                        if (updateOrderMap != null) {
                            purchaseOrderMapper.updatePurchaseOrderPayStatusByAliOrderNo(updateOrderMap);
                        }
                    }
                    break;
                case "LOGISTICS_BUYER_VIEW_TRACE"://物流单状态变更（买家视角）
                    //只更新状态信息,20230111这个禁用，改成定时任务通过接口去取物流信息，这边消息返回不全
                    /*Map<String, Object> orderLogisticsTracingModel = (Map<String, Object>) dataMap.get("OrderLogisticsTracingModel");
                    if (orderLogisticsTracingModel != null) {
                        String logisticsId3 = (String) orderLogisticsTracingModel.get("logisticsId");
                        String cpCode3 = (String) orderLogisticsTracingModel.get("cpCode");
                        String mailNo3 = (String) orderLogisticsTracingModel.get("mailNo");
                        String statusChanged3 = (String) orderLogisticsTracingModel.get("statusChanged");
                        updateMap.put("aliLogisticsCompanyName", cpCode3);
                        updateMap.put("aliPlace", cpCode3);
                        updateMap.put("aliLogisticsBillNo", mailNo3);
                        updateMap.put("aliLogisticsCode", logisticsId3);
                        updateMap.put("aliLogisticsState", statusChanged3);
                        JSONArray orderLogsItems = (JSONArray) orderLogisticsTracingModel.get("orderLogsItems");
                        if (orderLogsItems != null && orderLogsItems.size() > 0) {
                            for (int i = 0; i < orderLogsItems.size(); i++) {
                                JSONObject itemObj = orderLogsItems.getJSONObject(i);
                                String orderId3 = itemObj.get("orderId").toString();
                                updateMap.put("aliOrderNumber", orderId3);
                                purchaseOrderMapper.updatePurchaseOrderInfoByAliOrderNo(updateMap);
                            }
                        }
                    }*/
                    break;
                case "ORDER_BUYER_VIEW_ORDER_SUCCESS"://1688交易成功（买家视角），这个20120111暂不处理，由每天获取订单信息处理
                    /*String orderId4 = dataMap.get("orderId").toString();
                    String currentStatus4 = (String) dataMap.get("currentStatus");
                    //只更新状态信息
                    updateMap.put("aliOrderNumber", orderId4);
                    updateMap.put("aliState", currentStatus4);
                    purchaseOrderMapper.updatePurchaseOrderInfoByAliOrderNo(updateMap);
                    */
                    break;
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
        } catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API处理1688回调消息出错，具体错误信息为：" + ex.getMessage());
            logger.error("ECP_API处理1688回调消息出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
}
    }
}
